package controller

import (
	"encoding/base64"
	"errors"
	"github.com/sirupsen/logrus"
	"my-desktop/common"
	"my-desktop/config"
	"my-desktop/models"
	"my-desktop/service"
	"my-desktop/utils"
	"net/http"
	"strconv"
)

func Connect(w http.ResponseWriter, r *http.Request) {
	// 获取ssh密钥
	sshKeyEncode := r.Header.Get(config.Http.SshKeyHeader)

	// 获取参数
	params := common.GetRequestJsonParam(r)
	usernameEncode := params["username"].(string)
	passwordEncode := params["password"].(string)
	ipaddrEncode := params["IPAddr"].(string)
	nameEncode := params["name"].(string)

	// 前端参数为base64编码 需要解码
	usernameByte, err := base64.StdEncoding.DecodeString(usernameEncode)
	passwordByte, err := base64.StdEncoding.DecodeString(passwordEncode)
	ipaddrByte, err := base64.StdEncoding.DecodeString(ipaddrEncode)
	nameByte, err := base64.StdEncoding.DecodeString(nameEncode)
	sshKeyByte, err := base64.StdEncoding.DecodeString(sshKeyEncode)

	username := string(usernameByte)
	password := string(passwordByte)
	ipaddr := string(ipaddrByte)
	name := string(nameByte)
	sshKey := string(sshKeyByte)

	// 检查token
	tokenString, err := common.GetToken(r, config.Http.Token)
	if err != nil {
		logrus.Warn("用户没有token")
		common.Error(w, models.LoginExpired, "用户没有权限访问", err)
		return
	}

	user, err := utils.ParseToken(tokenString)
	if err != nil {
		logrus.Warn("用户token解析失败")
		common.Error(w, models.LoginExpired, "用户没有权限访问", err)
		return
	}

	mapKey := strconv.FormatUint(user.UserID, 10) + ":" + name
	err = service.Connect(user.UserID, name, username, password, ipaddr, mapKey, sshKey)
	if err != nil {
		logrus.Warn("主机连接失败")
		common.Error(w, models.UnknownError, "主机连接失败", err)
		return
	}
	common.Success(w, models.Success, "连接成功", "")
}

func ExecuteShell(w http.ResponseWriter, r *http.Request) {
	params := common.GetRequestJsonParam(r)
	shell := params["shell"].(string)
	name := params["name"].(string)

	// 检查token
	tokenString, err := common.GetToken(r, config.Http.Token)
	if err != nil {
		logrus.Warn("用户没有权限访问")
		common.Error(w, models.LoginExpired, "用户没有权限访问", err)
		return
	}

	user, err := utils.ParseToken(tokenString)
	if err != nil {
		logrus.Warn("用户没有权限访问")
		common.Error(w, models.LoginExpired, "用户没有权限访问", err)
		return
	}

	mapKey := strconv.FormatUint(user.UserID, 10) + ":" + name
	data := service.ExecuteShell(shell, mapKey)
	if len(data) == 0 {
		common.Error(w, models.UnknownError, "执行shell失败", errors.New("执行shell失败"))
	} else {
		common.Success(w, models.Success, "", data)
	}
}
